package com.example.watchcat2k.finalproject;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;
import retrofit2.http.Path;

public class ChangeInfoActivity extends AppCompatActivity {

    private ImageView back;
    private Button send;
    private ImageView pick_my_icon;
    private EditText change_my_name;
    private EditText change_my_des;
    private User_basic_info my_info;
    private User_basic_info old_info;
    private Boolean has_change = false;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_personal_info);

        init();


        set_click();
    }

    void init(){
        Intent intent = getIntent();
        my_info = (User_basic_info) intent.getSerializableExtra("user");
        old_info = new User_basic_info(my_info.getUsername(), my_info.getDescription(), my_info.getName(), my_info.getIcon());
        back = (ImageView)findViewById(R.id.change_my_info_back);
        send = findViewById(R.id.change_info_send);
        pick_my_icon = findViewById(R.id.change_my_icon);
        change_my_name = findViewById(R.id.change_my_name);
        change_my_des = findViewById(R.id.change_my_desc);

        //初始化用户信息
        change_my_name.setText(my_info.getName());
        change_my_des.setText(my_info.getDescription());
        Bitmap bm = null;
        byte[] bytes = Base64.decode(my_info.getIcon(), Base64.DEFAULT);
        bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        pick_my_icon.setImageBitmap(bm);


    }

    void set_click(){
        pick_my_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            }
        });


        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(change_my_name.getText().toString().equals("")){
                    Toast.makeText(ChangeInfoActivity.this,"昵称不可为空",Toast.LENGTH_SHORT).show();
                }
                else{
                    //是否已经修改过
                    if(has_change || !change_my_name.getText().toString().equals(my_info.getName()) ||
                            !change_my_des.getText().toString().equals(my_info.getDescription())){
                        if(change_my_des.getText().toString().equals("")){
                            my_info.setName(change_my_name.getText().toString());
                            my_info.setDescription("该用户暂无个人描述");
                        }
                        else {
                            my_info.setName(change_my_name.getText().toString());
                            my_info.setDescription(change_my_des.getText().toString());
                        }



                        //sent_back_intent和myinfo是返回去主页面的，change_packet是发送给服务器的
                        change_my_info_packet change_packet = new change_my_info_packet(my_info.getUsername(),my_info.getName(),
                                my_info.getDescription(), my_info.getIcon());

                        //网络请求
                        try {
                            OkHttpClient build = new OkHttpClient.Builder()
                                    .connectTimeout(2, TimeUnit.SECONDS)
                                    .readTimeout(2, TimeUnit.SECONDS)
                                    .writeTimeout(2, TimeUnit.SECONDS)
                                    .build();

                            Retrofit retrofit = new Retrofit.Builder()
                                    .baseUrl("http://129.204.116.253:8080")

                                    .addConverterFactory(GsonConverterFactory.create())

                                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                                    // build 即为okhttp声明的变量，下文会讲
                                    .client(build)

                                    .build();

                            ChangeMyinfo service = retrofit.create(ChangeMyinfo.class);

                            service.postChange(my_info)
                                    .subscribeOn(Schedulers.io())//请求在新的线程中执行
                                    .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                                    .subscribe(new DisposableObserver<Send_Blog_Confirm_Packet>() {
                                        @Override
                                        public void onNext(Send_Blog_Confirm_Packet send_blog_confirm_packet) {
                                            if(send_blog_confirm_packet.isStatus()){ //发布成功
                                                //修改成功返回主页面
                                                Intent sent_back_intent = new Intent();
                                                sent_back_intent.putExtra("has_change", true);
                                                sent_back_intent.putExtra("user", my_info);

                                                //设置返回数据
                                                ChangeInfoActivity.this.setResult(RESULT_OK, sent_back_intent);
                                                //关闭Activity
                                                ChangeInfoActivity.this.finish();
                                            }
                                            else { //发布失败
                                                Toast.makeText(ChangeInfoActivity.this, "修改失败: " + send_blog_confirm_packet.getMessage(), Toast.LENGTH_SHORT).show();
                                                my_info.setName(old_info.getName());
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            Toast.makeText(ChangeInfoActivity.this, "修改失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                                            my_info.setName(old_info.getName());
                                            my_info.setDescription((old_info.getDescription()));
                                            Log.i("test", "onError: "+e.toString());
                                        }

                                        @Override
                                        public void onComplete() {

                                        }
                                    });
                        }catch (Exception o){
                            Toast.makeText(ChangeInfoActivity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();

                            Log.i("test", "onError: "+o.toString());
                        }



                    }
                    else {
                        Toast.makeText(ChangeInfoActivity.this,"未修改过个人信息",Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder back_info = new AlertDialog.Builder(ChangeInfoActivity.this);
                back_info.setTitle("退出").setMessage("此操作会放弃所有修改，是否继续?").setPositiveButton("确定",
                        new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialoginterface, int i){
                                Intent sent_back_intent = new Intent();
                                //设置返回数据
                                ChangeInfoActivity.this.setResult(RESULT_OK, sent_back_intent);
                                //关闭Activity
                                ChangeInfoActivity.this.finish();
                            }
                        }).setNegativeButton("取消",
                        new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialoginterface, int i) {

                            }
                        }).create().show();

            }
        });
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            Uri uri = data.getData();
            pick_my_icon.setImageBitmap(get_image_Bitmap(uri));
            my_info.setIcon(Bitmap_to_base64(get_image_Bitmap(uri)));
            has_change = true;
        }
        else{
            Toast.makeText(ChangeInfoActivity.this,"取消选择",Toast.LENGTH_SHORT).show();
        }
    }


    private String Bitmap_to_base64(Bitmap bitmap){
        ByteArrayOutputStream a = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, a);
        if(a.toByteArray().length > 20000){
            a.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, a);
        }

        String result = Base64.encodeToString(a.toByteArray(), Base64.DEFAULT);
        return result;
    }

    //将uri转换成bitmap
    private Bitmap get_image_Bitmap(Uri uri){

        try{
            // 读取本地图库uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
            return bitmap;
        }
        catch (Exception e) {
            Toast.makeText(ChangeInfoActivity.this,"图片选取失败",Toast.LENGTH_SHORT).show();
            return null;
        }
    }

//Send_Blog_Confirm_Packet在这里是通用的
    public interface ChangeMyinfo{
        @POST("/personalData")
        Observable<Send_Blog_Confirm_Packet> postChange(@Body User_basic_info user_basic_info);
    }


}
